package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Person;
import com.example.demo.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PersonController {
    @Autowired  //注入mapper
    private PersonMapper personMapper;
//mybatisxie写法
//    @GetMapping("/person")
//    public List query(){
//        List<Person> list = personMapper.select();
//        System.out.print(list);
//        return list;
//    }
//    @PostMapping("/save")
//    public String save(Person person){
//       int i = personMapper.insert(person);
//       if(i>0){
//           return "成功";
//       }else{
//           return "失败";
//       }
//    }

    @GetMapping("/person")
    public Map<String, Object> query(@RequestParam(value = "username", required = false) String username) {
        // 创建分页对象，查找第2页，每页3条数据
        Page<Person> page = new Page<>(1, 10);

        // 创建条件构造器
        QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username); // 添加查询条件
        }

        // 执行查询
        personMapper.selectPage(page, queryWrapper);

        // 获取当前页的记录
        List<Person> persons = page.getRecords();

        // 输出分页信息
        System.out.println("总记录数: " + page.getTotal());
        System.out.println(page);

        // 返回结果，包括当前页的记录和总记录数
        Map<String, Object> response = new HashMap<>();
        response.put("total", page.getTotal()); // 总数量
        response.put("records", persons); // 当前页记录

        return response; // 返回结果
    }

    @PostMapping("/save")
    public String save(Person person){
       int i = personMapper.insert(person);
       if(i>0){
           return "成功";
       }else{
           return "失败";
       }
    }

    @PostMapping("/delete")
    public String delete(String id){
        int i =personMapper.deleteById(id);
        System.out.print(i);
        return "成功";
    }

    @PostMapping("/getPersonById")
    public Person update(Integer id){
       return personMapper.selectById(id);
    }

    @PostMapping("/updatePerson")
    public int updateById(Person person) {
        // userMapper 是你的 Mapper 接口实例
        return personMapper.updateById(person);
    }
}
